<!--
 * @Author: wanglidong
 * @Date: 2021-04-08 09:22:42
 * @LastEditTime: 2023-02-14 15:44:18
 * @LastEditors: wanglidong
 * @Description: 项目日志
 * @nbsg
-->
<template>
  <div>
    <div class="model-title-css">
      <div class="title">项目日志</div>
    </div>
    <div class="background_wrap">
      <div class="operate_wrap flexDiv">
        <div class="flex-left">
          <el-button type="primary" size="small" class="add buildButtonStyle" @click="showDetailDialog('build')" v-permission="permission.add">
            <i class="iconfont icon-icon_add"></i>&nbsp;新增
          </el-button>
        </div>
        <div class="flex-right">
          <!-- <el-select
            v-on:change="fixQueryA()"
            class="select"
            size="small"
            value-key="id"
            v-model="search.company"
            placeholder="选择公司"
            style="margin-right: 15px"
            clearable
          >
            <el-option
              v-for="item in projectTree"
              :key="item.id"
              :label="item.name"
              :value="item"
            >
            </el-option>
          </el-select> -->
          <el-select v-on:change="fixQueryB()" class="select" size="small" value-key="id" v-model="search.projectId" placeholder="选择项目" clearable>
            <el-option v-for="item in search.company.children" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>

          <el-date-picker class="datePicker" v-model="searchDates" type="daterange" format="yyyy-MM-dd" unlink-panels value-format="yyyy-MM-dd" range-separator="至" start-placeholder="选择开始日期" end-placeholder="选择结束日期" clearable @change="onChangeTime">
          </el-date-picker>

          <el-button class="search" size="small" @click="getList(true)">
            <i class="iconfont icon-sousuo"></i> 搜索
          </el-button>
        </div>
      </div>
      <div class="list_wrap WholeScroll">
        <el-table class="project-management-info auto-flex-table" :border="true" :row-class-name="tableRowStyleName" :cell-class-name="tableCellStyleName" :header-cell-class-name="tableHeaderCellStyleName" :stripe="true" ref="multipleTable" :data="list" tooltip-effect="dark" style="width: 100%; font-family: PingFangSC-Regular; font-size: 14px;" @cell-click="cellClick">
          <el-table-column label="序号" type="index" align="center" width="60">
            <template slot-scope="scope">
              {{ scope.$index + search.pageIndex * search.pageSize + 1 }}
            </template>
          </el-table-column>
          <el-table-column show-overflow-tooltip prop="projectName" label="项目名称" min-width="160">
          </el-table-column>

          <!-- <el-table-column show-overflow-tooltip prop="affiliationStageName" label="所属阶段" min-width="140"></el-table-column> -->

          <!-- <el-table-column show-overflow-tooltip prop="itemName" label="事项名称" min-width="140"></el-table-column> -->

          <!-- <el-table-column show-overflow-tooltip prop="content" label="事项内容" min-width="140"></el-table-column> -->

          <el-table-column show-overflow-tooltip prop="createName" label="记录人" width="100"></el-table-column>

          <el-table-column label="文件预览" align="center" width="80">
            <template slot-scope="scope">
              <div class="table-iconfont-box row-i-hover-css">
                <i class="iconfont icon-a-wenjian1" v-if="scope.row.file&&scope.row.file.length>0" v-on:click="showFiles(scope.row,'项目日志')"></i>
              </div>
            </template>
          </el-table-column>

          <el-table-column show-overflow-tooltip prop="createTime" label="创建日期" width="170"></el-table-column>

          <el-table-column show-overflow-tooltip label="操作" width="280">
            <template slot-scope="scope">
              <el-button size="mini" class="menu_icon iconfont icon-icon_look action_color1" v-permission="permission.show" @click="handleClickDeal({ type: 'show', name: '查看', detailId: scope.row.id })">&nbsp;查看</el-button>
              <el-button size="mini" class="menu_icon iconfont icon-xiugai-copy action_color1" v-permission="permission.edit" @click="handleClickDeal({ type: 'update', name: '修改', detailId: scope.row.id })">&nbsp;修改</el-button>
              <el-button size="mini" class="menu_icon iconfont icon-shanchu action_color2" v-permission="permission.del" @click="handleClickDeal({ type: 'delete', name: '删除', detailId: scope.row.id })">&nbsp;删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination style="text-align: right; margin-top: 20px" layout="prev, pager, next" :page-size="search.pageSize" :total="search.pageSum" :current-page="search.pageIndex + 1" @current-change="paginationChange"></el-pagination>
      </div>
    </div>
    <Detail :postDetail="postDetailData" @reloadList="getList(true)"></Detail>

    <!-- 详情弹框 -->
    <el-dialog width="600px" class="approveDialog" :visible.sync="showFileDialog" :modal-append-to-body="false" :close-on-click-modal="false" append-to-body>
      <span slot="title">
        <i class="iconfont icon-a-wenjian1"></i>
        <span>附件</span>
      </span>
      <el-table v-loading="loading" element-loading-text="拼命加载中" element-loading-spinner="el-icon-loading" element-loading-background="rgba(0, 0, 0, 0.8)" :border="true" :header-cell-style="{padding: '0',height:'38px',backgroundColor: '#f2f2f2',textAlign:'center',borderColor: '#d4d4d4'}" :cell-style="{padding: '6px 0',textAlign:'center',borderColor: '#d4d4d4'}" ref="multipleTable" :data="nowFileList" style="width: 100%; font-family: PingFangSC-Regular; font-size: 14px;" @selection-change="handleSelectionChange">
        <el-table-column show-overflow-tooltip label="序号" type="index" width="60">
        </el-table-column>
        <el-table-column show-overflow-tooltip label="文件名" style="text-align: center" width="320">
          <template slot-scope="scope">
            <div style="text-align: center;" v-html="scope.row.fileName"></div>
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip min-width="20%" label="操作">
          <template slot-scope="scope">
            <el-tooltip class="item" effect="light" content="查看" placement="top">
              <div class="menu_icon" @click="viewFile(scope.row.id)" style="display: inline;cursor:pointer;margin-right: 5px"><i class='iconfont icon-icon_look'></i></div>
            </el-tooltip>
            <el-tooltip class="item" effect="light" content="下载" placement="top">
              <div class="menu_icon" @click="dlFile(scope.row)" style="display: inline;cursor:pointer"><i class='iconfont icon-icon-xiazai'></i></div>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <div slot="footer" class="dialog-footer">
        <!--新建和编辑的暂存上报-->
        <el-button size="small" @click="showFileDialog=false"><i class="iconfont icon-icon_cancel"></i> 关 闭
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import selectProjectAndSection from '@/mixins/selectProjectAndSection';
import projectSectionInfo from "@/api/buss/common";
import {
  tableRowStyleGol,
  tableCellStyleGol,
  tableHeaderCellStyleGol,
  doCreateObject
} from '@/utils/publicFun';
export default {
  name: 'projectLog',
  mixins: [selectProjectAndSection],
  components: {
    Detail: require('./projectLog-detail')
      .default
  },
  data() {
    let permissionBaseCode = "1001030";
    return {
      loading: false,
      tableRowStyleName: tableRowStyleGol,
      tableCellStyleName: tableCellStyleGol,
      tableHeaderCellStyleName: tableHeaderCellStyleGol,
      permission: {
        add: [`${permissionBaseCode}:add`],
        show: ['100', `${permissionBaseCode}:getOne`],
        edit: ['100', `${permissionBaseCode}:edit`],
        del: ['100', `${permissionBaseCode}:del`],
        listPage: ['100', `${permissionBaseCode}:listPage`],
      },
      searchDates: [],
      search: {
        pageIndex: 0,
        pageSize: 10,
        pageSum: 0,
        sortField: 'updateTime',
        buildCompanyId: '',
        projectId: '',
        itemName: '',
        endTime: '',
        beginTime: '',
        company: { children: [] },
        project: { children: [] },

      }, // 搜索参数
      companyTree: [],
      projectTree: [],
      contsectTree: [],
      measurePhase: [],
      list: [
      ],
      postDetailData: {
        show: false,
        type: 'build'
      },
      showFileDialog: false,
      fileTitle: '',
      nowFileList: [],
    };
  },
  created() {
    this.fetchWorkSectionList(() => { this.getList(); });
  },
  methods: {
    //预览
    viewFile(e) {
      this.loading = true
      this.$httpGet('/file-server/file/preview?id=' + e).then(response => {
        this.loading = false;
        //  如果是minio地址路径，则调用kkview
        if (!response.data.startsWith("/")) {
          window.open(PREVIEW_URL + '/onlinePreview?url=' + encodeURIComponent(Base64.encode(response.data)));
        } else {
          //  如果是转换后的previewGetFile，浏览器直接打开
          window.open(response.data);
        }
      }).catch(res => {
        console.log(res)
        this.loading = false;
      })
    },
    //下载文件
    dlFile(e) {
      this.$publicUpload.checkFile(e.id, e.fileName)
    },
    handleSelectionChange(val) {
      this.selectedIds = []
      val.forEach(item => {
        this.selectedIds.push(item.id)
      })
    },
    onChangeTime() {
      if (this.searchDates) {
        this.search.beginTime = this.searchDates[0]
        this.search.endTime = this.searchDates[1]
      } else {
        this.search.beginTime = ''
        this.search.endTime = ''
      }

      this.getList(true)
    },
    /**
     * 修正查询参数并查询
     *
     * */
    fixQueryA() {
      if (this.search.company.children) {
        // this.search.project = this.search.company.children[0]
      } else {
        this.search.project = {};
      }
      this.fixQueryB();
    },
    fixQueryB() {
      if (this.search.project.children) {
        // this.search.section = this.search.project.children[0];
      } else {
        this.search.section = {};
      }
      this.getList();
      // this.fixQueryC()
    },

    /**
     * 获取工程类合同-施工列表
     */
    fetchWorkSectionList(callback) {
      projectSectionInfo.getProjSecTreeAll().then(res => {
        if (res.code === 200) {
          this.$set(this.search.company, 'children', res.data);
          if (this.$headerSearch) {
            this.$set(this.search, 'projectId', this.changeHeaderProject);
            // console.log(this.search,66665554);
            // this.projectTree.forEach((item) => {
            //   if (item.id === this.search.projectId) {
            //     this.sectionTree = item.children
            //   }
            // })
            this.fixQueryB()
          }
        } else {
          this.$messageError(res.data.message);
        }
      }).catch(() => {
        this.$messageError('请求获取工程类合同-施工列表失败');
      });
      // if (callback) callback()
      // this.fixQueryA()
      // this.$httpGet('/buss/measurephaseMaster/getMeasurePhaseTree').then(res => {
      //   if (res.code == 200) {
      //     this.projectTree = JSON.parse(JSON.stringify(res.data))
      //     let projectTree2 = res.data
      //     console.log(projectTree2 ,'projectTree2 ');
      //     projectTree2.forEach(item => {
      //       if(item.children){
      //         this.search.company.children.push({})
      //       }
      //     });
      //     // this.search.company = projectTree2[0]
      //     console.log( this.search.company.children,' this.search.company');


      //   } else {
      //     console.log(res.msg)
      //     this.$messageError(res.msg)
      //   }
      // }).catch(e => {
      //   console.log(e)
      //   this.$messageError('请求获取工程类合同-施工列表失败')
      // })
    },


    //切换分页器
    paginationChange(index) {
      this.search.pageIndex = index - 1;
      this.getList();
    },
    //判断浏览器高度
    checkWindowHeight() {
      let height = $(window).height();
      if (height > 920) {
        this.search.pageSize = 15;
      }
      if (height < 920) {
        this.search.pageSize = 10;
      }
    },
    // 获取列表 api
    getList(reload) {
      if (reload) {
        this.search.pageIndex = 0;
      }
      this.list = [];
      let postData = {
        pageNo: this.search.pageIndex,
        pageSize: this.search.pageSize,
        projectId: this.search.projectId,
        itemName: this.search.itemName,
        endTime: this.search.endTime,
        beginTime: this.search.beginTime,
      };
      this.$httpPost(
        '/buss/projectLog/getList',
        postData
      )
        .then((res) => {
          if (res.status === 1) {
            this.list = res.data.content;
            console.log(res, 'res');
            this.search.pageSum = parseInt(res.data.totalElements);
          } else {
            this.$messageError(res.data.message);
          }
        })
        .catch((res) => {
          console.log('请求出现错误', res);
          this.$messageError(this.$route.name + '请求失败');
        });
    },
    // 事件处理的api请求
    sealDealHttp(url, query, param, callback) {
      this.$httpPost(url + query, param)
        .then((res) => {
          if (res.status === 1) {
            if (callback) callback(res);
            // 重新获取数据
            setTimeout(() => {
              this.getList(true);
            }, 1000);
          } else {
            this.$messageError(res.message);
          }
        })
        .catch((res) => {
          console.log('请求出现错误', res);
          console.log(res);
        });
    },
    // 显示详情弹窗 不同状态
    showDetailDialog(flag, params) {
      console.log(flag, params);
      switch (flag) {
        case 'build':
          this.postDetailData = {
            show: true,
            type: 'build',
            params: params
          };
          break;
        case 'update':
          this.postDetailData = {
            show: true,
            type: 'edit',
            params: params
          };
          break;
        //查看
        case 'show':
          this.postDetailData = {
            show: true,
            type: 'check',
            params: params
          };
          break;
        //文件上传
        case 'upload':
          this.postDetailData = {
            show: true,
            type: 'upload',
            params: params
          };
          break;
        case 'history':
          this.postDetailData = {
            show: true,
            type: 'history',
            params: params
          };
          break;
        case 'download':
          this.postDetailData = {
            show: true,
            type: 'download',
            params: params
          };
          break;
      }
    },
    // 列表的操作流程
    handleClickDeal(res) {
      let type = res.type;
      let detailId = res.detailId;
      let url = res.url;
      let name = res.name;
      let actions = res.actions;
      this.boundContractId = detailId;
      // console.log(res)
      switch (type) {
        // 查看
        case 'show':
          // 显示详情弹窗
          this.showDetailDialog(type, {
            detailId: detailId,
            actions: actions
          });
          break;
        // 修改
        case 'update':
          // 显示详情弹窗
          this.showDetailDialog(type, {
            detailId: detailId,
            actions: actions
          });
          break;
        // 删除
        case 'delete':
          if (detailId === '') {
            this.$messageError('请先选择要删除的记录！');
            return;
          }
          this.$confirm('确定是否删除？', '提示', {
            confirmButtonClass: 'iconfont icon-icon_ok',
            cancelButtonClass: 'iconfont icon-icon_cancel',
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'info'
          })
            .then(() => {
              this.sealDealHttp(
                `/buss/projectLog/delete`,
                ``,
                {
                  ids: detailId.split(',')
                },
                () => {
                  this.$messageSuccess('删除成功!');
                }
              );
            })
            .catch(() => {
            });
          console.log('请求出现错误');
          break;
      }
    },
    // 点击单元格
    cellClick(row, column, cell, event) {
      // console.log(row, column, cell, event)
      // console.log(column);
      if (column.property === 'projectName') {
        this.handleClickDeal({
          type: 'show',
          detailId: row.id,
          actions: row.actions
        });
      }
    },
    showFiles(row, title) {
      console.log(row, '=============')
      this.fileTitle = title
      this.nowFileList = row.file
      if (this.nowFileList) {
        this.showFileDialog = true
      }
    },
  }
};
</script>

<style scoped lang="scss">
.top {
  width: 100%;
  height: 40px;

  .title {
    float: left;
    font-family: PingFangSC-Regular;
    font-size: 18px;
    font-weight: 600;
  }
}

.operate_wrap {
  width: 100%;

  .select {
    width: 200px;
    margin-right: 15px;
  }
  .datePicker {
    width: 350px;
    margin-right: 15px;
  }
  .input {
    width: 200px;
    margin: 0 15px;
  }

  .search {
    width: 88px;
    color: #fff;
    margin-left: 0 !important;
  }
}

.list_wrap {
  margin-top: 20px;
}

.navigation {
  width: 100%;
  height: 40px;
  box-sizing: border-box;
  border-bottom: 1px solid #313e50;
  margin-top: 5px;

  .el-button {
    height: 40px;
    background: #374256;
    border: 1px solid #374256;
    font-family: PingFangSC-Regular;
    border-radius: 5px 5px 0 0;
    min-width: 95px;
    font-size: 14px;
    color: #8190a7;

    &:hover {
      background-color: #f2f2f2;
    }

    &[selected] {
    }
  }

  .el-button + .el-button {
    margin-left: 0;
  }
}
.icon-a-wenjian1 {
  font-size: 26px;
}
</style>
